package com.zhiying.web.service.impl;

import com.zhiying.shiro.AuthenticationInfo;
import com.zhiying.shiro.AuthorizationInfo;
import com.zhiying.web.service.LoginService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.Set;

@Service
public class LoginServiceImpl implements LoginService {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoginServiceImpl.class);

    @Override
    public String autoLogin(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("通过了拦截器");
        return "shiro authorization and authentication success";
    }

    @Override
    public String loginByNameAndPsw(HttpServletRequest request, HttpServletResponse response) {
        String userName = request.getParameter("username");
//        String password = request.getParameter("password");
//        String encodePsw = MD5Util.md5Encode(password+Constants.SECRET_KEY);
        HttpSession session = request.getSession(true);

        Set<String> roleSet = new HashSet<>();
        Set<String> resourceSet = new HashSet<>();
        //设置一个admin的模拟角色
        roleSet.add("Admin");
        //设置一个登陆的资源
        resourceSet.add("button:login:handler");
        AuthorizationInfo authorization = new AuthorizationInfo(roleSet, resourceSet);
        String remoteAdd = request.getRemoteAddr();
        AuthenticationInfo authentication = new AuthenticationInfo(userName, remoteAdd);
        //sessionId应该放到cookie值里，然后设置cookie过期时间
        session.setAttribute("Admin", authentication);
        session.setAttribute("Authc", authorization);
        session.setMaxInactiveInterval(10 * 60);

        Cookie[] cookies = request.getCookies();

        for (Cookie cookie : cookies) {
            if (StringUtils.equals(cookie.getName(), "JSESSIONID")) {
                //cookie失效时间10分钟 这期间关掉浏览器再开，浏览器还是会记住登录
                //cookie默认有效时间为浏览器不关掉的时间
                cookie.setMaxAge(10 * 60);
                //JSESSIONID是sessionId 是后台会话id在客户端保留的标识 重新setValue会导致session找不到
//                cookie.setValue("username");
                response.addCookie(cookie);
            }
        }
        Cookie cookie = new Cookie("username",userName);
        cookie.setMaxAge(10*60);
        response.addCookie(cookie);
        return "success";
    }


}

